package com.duoshu.grj.sosoliuda.ui.player;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aliyun.vodplayer.media.AliyunPlayAuth;
import com.aliyun.vodplayer.media.AliyunVodPlayer;
import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.duoshu.grj.sosoliuda.R;
import com.duoshu.grj.sosoliuda.model.StringRequest;
import com.duoshu.grj.sosoliuda.model.bean.StepResponse;
import com.duoshu.grj.sosoliuda.model.util.HttpSubscriber;
import com.duoshu.grj.sosoliuda.ui.view.ActionBar;
import com.duoshu.grj.sosoliuda.ui.view.LoadingFrameView;
import com.duoshu.grj.sosoliuda.utils.DateUtil;
import com.duoshu.grj.sosoliuda.utils.EmptyUtils;
import com.duoshu.grj.sosoliuda.utils.LogUtils;
import com.duoshu.grj.sosoliuda.utils.NetUtils;
import com.duoshu.grj.sosoliuda.utils.ToastUtils;
import com.zhy.autolayout.utils.AutoUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.aliyun.vodplayer.media.IAliyunVodPlayer.PlayerState.Paused;

/**
 * 项目名称：Sosoliuda
 * 类描述：播放控件
 * 创建人：周作威
 * 创建时间：2017/5/18
 */

public class PlayerView extends RelativeLayout {
    private static final String TAG = PlayerView.class.getSimpleName();
    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;
    @BindView(R.id.action_bar)
    ActionBar actionBar;
    @BindView(R.id.app_video_currentTime)
    TextView appVideoCurrentTime;
    @BindView(R.id.app_video_seekBar)
    SeekBar appVideoSeekBar;
    @BindView(R.id.app_video_endTime)
    TextView appVideoEndTime;
    @BindView(R.id.app_video_bottom_box)
    LinearLayout appVideoBottomBox;
    @BindView(R.id.app_video_fl)
    FrameLayout app_video_fl;
    @BindView(R.id.loading_fv)
    LoadingFrameView loadingFv;
    @BindView(R.id.app_video_bottom)
    ImageView app_video_bottom;
    @BindView(R.id.player_suofang)
    ImageView player_suofang;

    private Activity activity;
    private View contentView;
    boolean isPlayer;
    String player_id;
    private String player_title;
    private AliyunVodPlayer aliyunVodPlayer;
    private int video_index;
    private NetChangeReceiver netChangeReceiver;

    private View playIconView;//播放按钮

    public PlayerView(Context context) {
        this(context, null);
    }

    public PlayerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        activity = (Activity) context;
        //初始化view和其他相关的
        initView();
    }

    private void initView() {
        contentView = View.inflate(activity, R.layout.playerview, this);
        playIconView = View.inflate(activity, R.layout.layout_video_play_icon, null);
        AutoUtils.auto(contentView);
        ButterKnife.bind(this, contentView);
        actionBar.addLeftTextView(0, R.drawable.dbx);
        actionBar.setLeftViewListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    activity.finish();
                } else {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
        });
        actionBar.getLeftView().setTextColor(Color.WHITE);
        actionBar.setBackground(R.color.c00000000);
        aliyunVodPlayer = new AliyunVodPlayer(getContext());
        aliyunVodPlayer.setOnPreparedListener(new IAliyunVodPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                //准备成功之后可以调用start方法开始播放
                LogUtils.e("Player_onPrepared", "准备成功之后可以调用start方法开始播放");
                app_video_fl.setVisibility(VISIBLE);
                if (isPlayer) {
                    start();
                }
                loadingFv.setContainerShown(true, 0);
                LogUtils.e("aliyunVodPlayer.getMediaInfo()","aliyunVodPlayer.getMediaInfo()==="+aliyunVodPlayer.getMediaInfo().getTitle());
                if (EmptyUtils.isNotEmpty(aliyunVodPlayer.getMediaInfo().getTitle())) {
                    actionBar.setLeftViewText(aliyunVodPlayer.getMediaInfo().getTitle());
                }
                showVideoProgressInfo();
                showVideoBottomBox(0);
            }
        });
        aliyunVodPlayer.setOnErrorListener(new IAliyunVodPlayer.OnErrorListener() {
            @Override
            public void onError(int arg0, int arg1) {
                LogUtils.e("Player_onError", "失败！！！！原因：" + arg0);
                error();

            }
        });
        aliyunVodPlayer.setOnCompletionListener(new IAliyunVodPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                LogUtils.e("Player_onCompletion", "播放结束--- ");
               /* loadingFv.setRepeatIcon(null);
                loadingFv.setRepeatInfo("播放结束");
                loadingFv.setRepeatBt("重新播放");
                loadingFv.setErrorShown(true, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reset();
                    }
                });*/
                playIconView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reset();
                    }
                });
                loadingFv.setCustomView(playIconView);
                loadingFv.setCustomShown(true);
                stopUpdateTimer();
                updateBufferingProgress(100);
                showVideoBottomBox(0);
                app_video_fl.setVisibility(GONE);
            }
        });
        aliyunVodPlayer.setOnBufferingUpdateListener(new IAliyunVodPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(int percent) {
                LogUtils.e("Player_onBufferingUpdate", "缓冲进度更新--- " + percent);
                updateBufferingProgress(percent);
            }
        });
        aliyunVodPlayer.setOnLoadingListener(new IAliyunVodPlayer.OnLoadingListener() {
            @Override
            public void onLoadStart() {
                LogUtils.e("Player_onLoadStart", "缓冲开始--- ");
                loadingFv.setProgressShown(true);
                loadingFv.setEmptyInfo("正在缓冲0%");
            }

            @Override
            public void onLoadEnd() {
                LogUtils.e("Player_onLoadEnd", "缓冲结束--- ");
                loadingFv.setContainerShown(true, 0);
            }

            @Override
            public void onLoadProgress(int i) {
                LogUtils.e("Player_onLoadProgress", "缓冲--- " + i);
                loadingFv.setProgressShown(true);
                loadingFv.setEmptyInfo("正在缓冲" + i + "%");
            }
        });
        aliyunVodPlayer.setDisplay(surfaceView.getHolder());
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                LogUtils.e(TAG, "surfaceCreated");
                aliyunVodPlayer.setDisplay(holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                LogUtils.e(TAG, "surfaceChanged");
                aliyunVodPlayer.surfaceChanged();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                LogUtils.e(TAG, "surfaceDestroyed");
            }
        });
        aliyunVodPlayer.setOnSeekCompleteListener(new IAliyunVodPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete() {
                LogUtils.e("onSeekComplete", "onSeekComplete" + aliyunVodPlayer.getCurrentPosition());
//                start();
            }
        });
        appVideoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LogUtils.e("onProgressChanged", fromUser + "====" + progress + "====" + aliyunVodPlayer.getDuration());
                if (fromUser) {
                    aliyunVodPlayer.seekTo(progress);
//                    pause();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        app_video_bottom.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showVideoBottomBox(0);
                if (aliyunVodPlayer.isPlaying() || aliyunVodPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Prepared) {
                    if (aliyunVodPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Paused || aliyunVodPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Prepared) {
                        start();
                    } else {
                        pause();
                    }
                } else {
                    reset();
                }
            }
        });
        app_video_fl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (video_index > 5) {
                    showVideoBottomBox(0);
                } else {
                    showVideoBottomBox(6);
                }
            }
        });
        player_suofang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    if (null != activity) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    if (null != activity) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                }
            }
        });
        registerNetReceiver();
    }

    //播放
    public void setPlayer(String player_id, String player_title, boolean isPlayer) {
        if (NetUtils.getNetworkType(activity) == 2 || NetUtils.getNetworkType(activity) == 4)
            ToastUtils.toastSingle("当前使用的是4G流量~！");
        this.player_id = player_id;
        this.isPlayer = isPlayer;
        this.player_title = player_title;
        if (EmptyUtils.isNotEmpty(player_title)) {
            actionBar.setLeftViewText(player_title);
        }
        loadingFv.setEmptyInfo("正在加载中...");
        loadingFv.setProgressShown(true);
        StringRequest.getInstance().getVideoId(player_id).subscribe(new HttpSubscriber<StepResponse>() {
            @Override
            public void onNext(StepResponse response) {
                if (null != response && null != response.get_video_play_auth_response && null != response.get_video_play_auth_response.video_play_auth && EmptyUtils.isNotEmpty(response.get_video_play_auth_response.video_play_auth.play_auth)) {
                    AliyunPlayAuth.AliyunPlayAuthBuilder aliyunPlayAuthBuilder = new AliyunPlayAuth.AliyunPlayAuthBuilder();
                    aliyunPlayAuthBuilder.setVid(PlayerView.this.player_id);
                    aliyunPlayAuthBuilder.setQuality(IAliyunVodPlayer.QualityValue.QUALITY_ORIGINAL);
                    aliyunPlayAuthBuilder.setPlayAuth(response.get_video_play_auth_response.video_play_auth.play_auth);
                    aliyunVodPlayer.setAuthInfo(aliyunPlayAuthBuilder.build());
                    aliyunVodPlayer.prepareAsync();
                } else {
                    error();
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                error();
            }
        });

    }

    public void start() {
        aliyunVodPlayer.start();
        app_video_bottom.setImageResource(R.drawable.player_bofang);
    }

    public void pause() {
        aliyunVodPlayer.pause();
        app_video_bottom.setImageResource(R.drawable.player_zanting);
    }

    public void reset() {
        aliyunVodPlayer.reset();
//        if (TextUtils.isEmpty(play_auth)) {
        setPlayer(player_id, player_title, isPlayer);
//        } else {
//            setPlayAuth(play_auth);
//        }
    }

    public void error() {
       /* loadingFv.setRepeatIcon(null);
        loadingFv.setRepeatInfo("加载失败");
        loadingFv.setRepeatBt("重新加载");
        loadingFv.setErrorShown(true, new OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });*/

        playIconView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });
        loadingFv.setCustomView(playIconView);
        loadingFv.setCustomShown(true);
    }

    public void onResume() {
        //保存播放器的状态，供resume恢复使用。
        resumePlayerState();
    }

    public void onStop() {
        //onStop中记录下来的状态，在这里恢复使用
        savePlayerState();
    }

    //用来记录前后台切换时的状态，以供恢复。
    private IAliyunVodPlayer.PlayerState mPlayerState;

    private void resumePlayerState() {
        if (mPlayerState == Paused) {
            pause();
        } else if (mPlayerState == IAliyunVodPlayer.PlayerState.Started) {
            start();
        }
    }

    private void savePlayerState() {
        mPlayerState = aliyunVodPlayer.getPlayerState();
        if (aliyunVodPlayer.isPlaying()) {
            //然后再暂停播放器
            pause();
        }
    }

    public void onDestroy() {
        if (aliyunVodPlayer != null) {
            aliyunVodPlayer.release();
        }
        aliyunVodPlayer = null;
        unregisterNetReceiver();// 取消网络变化的监听
        stopUpdateTimer();
        progressUpdateTimer = null;
    }

    private void showVideoProgressInfo() {
        int curPosition = (int) aliyunVodPlayer.getCurrentPosition();
        appVideoCurrentTime.setText(DateUtil.formatTime(curPosition));
        int duration = (int) aliyunVodPlayer.getDuration();
        appVideoEndTime.setText(DateUtil.formatTime(duration));
        appVideoSeekBar.setMax(duration);
        appVideoSeekBar.setProgress(curPosition);
        startUpdateTimer();
    }

    private void startUpdateTimer() {
        progressUpdateTimer.removeMessages(0);
        progressUpdateTimer.sendEmptyMessageDelayed(0, 1000);
    }

    private void stopUpdateTimer() {
        progressUpdateTimer.removeMessages(0);
    }

    private void updateBufferingProgress(int percent) {
        int duration = (int) aliyunVodPlayer.getDuration();
        appVideoSeekBar.setSecondaryProgress((int) (duration * percent * 1.0f / 100));
    }

    public void showVideoBottomBox(int index) {
        video_index = index;
        actionBar.setVisibility(index > 5 ? GONE : VISIBLE);
        appVideoBottomBox.setVisibility(index > 5 ? GONE : VISIBLE);
    }

    private Handler progressUpdateTimer = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            showVideoProgressInfo();
            showVideoBottomBox(video_index + 1);
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        showVideoBottomBox(0);
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {                //转为竖屏了。
            player_suofang.setImageResource(R.drawable.player_fangda);
            //显示状态栏
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

//            //设置view的布局，宽高之类
//            ViewGroup.LayoutParams surfaceViewLayoutParams = surfaceView.getLayoutParams();
//            surfaceViewLayoutParams.height = (int) (UiUtil.getDisplayWidth(getContext()) * 9.0f / 16);
//            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {                //转到横屏了。
            player_suofang.setImageResource(R.drawable.player_suoxiao);
            //隐藏状态栏
            activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
//            //设置view的布局，宽高
//            ViewGroup.LayoutParams surfaceViewLayoutParams = surfaceView.getLayoutParams();
//            surfaceViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
//            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        }
    }

    /**
     * 注册网络监听器
     */
    private void registerNetReceiver() {
        if (netChangeReceiver == null) {
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            netChangeReceiver = new NetChangeReceiver();
            activity.registerReceiver(netChangeReceiver, filter);
        }
    }

    /**
     * 销毁网络监听器
     */
    private void unregisterNetReceiver() {
        if (netChangeReceiver != null) {
            activity.unregisterReceiver(netChangeReceiver);
            netChangeReceiver = null;
        }
    }

    /*********************************
     * 网络变化监听
     ************************************/
    public class NetChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetUtils.getNetworkType(activity) == 3) {// 网络是WIFI
            } else if (NetUtils.getNetworkType(activity) == 2 || NetUtils.getNetworkType(activity) == 4) {// 网络不是手机网络或者是以太网
                // TODO 更新状态是暂停状态
                ToastUtils.toastSingle("当前使用的是4G流量~！");
            } else if (NetUtils.getNetworkType(activity) == 1) {// 网络链接断开
                ToastUtils.toastSingle("网络连接已断开！");
            } else {
                ToastUtils.toastSingle("无网络连接！");
            }
        }
    }
}
